const { find: findOrgUnit } = require('./org-units')
const { list: listRooms } = require('./rooms')
const Mock = require('mockjs')

const LuckyMoney = []
const PreviewLuckyMoney = []
const roomsPage = listRooms(1, 150)
let id = 1
let id2 = 1
for (let i = 0; i < roomsPage.data.records.length; ++i) {
  const orgUnit = findOrgUnit(roomsPage.data.records[i].orgUnitId)
  LuckyMoney.push(Mock.mock({
    id: id++,
    orgUnitName: orgUnit.name,
    orgUnitId: roomsPage.data.records[i].orgUnitId,
    roomId: roomsPage.data.records[i].id,
    roomName: roomsPage.data.records[i].name,
    start: Mock.Random.datetime(),
    end: Mock.Random.datetime(),
    initAmount: i * 45,
    amount: i * 45 - i % 10
  }))
  PreviewLuckyMoney.push(Mock.mock({
    id: id2++,
    orgUnitName: orgUnit.name,
    orgUnitId: roomsPage.data.records[i].orgUnitId,
    roomId: roomsPage.data.records[i].id,
    roomName: roomsPage.data.records[i].name,
    start: Mock.Random.datetime(),
    end: Mock.Random.datetime(),
    initAmount: i * 45,
    amount: i * 45 - i % 10,
    playCount: Mock.Random.integer(3, 76)
  }))
}

function list(page, limit, orgUnitId, roomId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  roomId = roomId ? parseInt(roomId) : null
  let mocks = LuckyMoney.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    return !(roomId && item.roomId !== roomId)
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, data: { total: total, records: mocks }}
}

function listPreview() {
  return { success: true, data: { records: PreviewLuckyMoney, excludes: [168, 279] }}
}

module.exports = { list, listPreview }
